package MicronautTest;

import io.micronaut.context.annotation.Parameter;
import io.micronaut.core.io.Writable;
import io.micronaut.http.HttpHeaders;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.*;
import io.micronaut.http.multipart.StreamingFileUpload;
import io.micronaut.http.server.types.files.StreamedFile;
import io.reactivex.Single;

import javax.validation.constraints.NotBlank;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.logging.Logger;

@Controller("/")
public class HelloController {
    private Logger log = Logger.getLogger("HelloController");

    @Get("/hello")
    @Produces(MediaType.TEXT_PLAIN)
//    @Produces(MediaType.APPLICATION_JSON)
    public String hello() {
        log.info("Hello World");
        return "Hello World";
    }

    @Get("/hello2")
    @Produces(MediaType.TEXT_PLAIN)
//    @Produces(MediaType.APPLICATION_JSON)
    public String hello2(@Parameter String path) {
        log.info("Hello World2 path:" + path);
        return "Hello World2";
    }

    @Get("/hello3/{name}")
    public String hello3(@Parameter String path, @PathVariable String name) {
        log.info("Hello World3 path:" + path);
        log.info("Hello World3 name:" + name);
        return "{\"status\" : \"normal\"}";
    }

    @Get("file")
    public HttpResponse getFile(HttpRequest request) throws FileNotFoundException {
        String fileStr = request.getParameters().get("path");
        File file = new File(fileStr);
        MediaType fileType = MediaType.forFilename(file.getName());
        InputStream inputStream = new FileInputStream(file);

        StreamedFile streamedFile = new StreamedFile(inputStream, fileType);

        return HttpResponse.ok()
                .header(HttpHeaders.ACCEPT_RANGES, "bytes")
                .body(streamedFile);
    }

    @Get("/write/{name}")
    public Writable write(@NotBlank String name) {
        long tid = Thread.currentThread().getId();
        log.info("write tid:" + tid);

        return writer -> {
            long tid2 = Thread.currentThread().getId();
            log.info("writer tid:" + tid2);
            writer.append("hello writer");
            writer.write(" write()");
        };
    }

    @Post("/upload")
    Single<HttpResponse> upload(StreamingFileUpload file, @QueryValue String path) {
        log.info("upload");

        return Single.just(HttpResponse.ok());
    }



}
